<?php

use Yaf\Loader;

Loader::import(APP_PATH . '/vendor/phpQuery/phpQuery.php');

class WeChatOpenLoginModel
{

    private $userModel;


    private static $checkCode = [
        '408' => "用户未扫码",
        '404' => '用户未确认',
        '405' => '用户确认登录',
        '402' => 'uuid已经过期',
    ];

    private $wxCode;

    /**
     * gtr
     * @var string
     */
    private $gTk;

    /**
     * @param string $gTk
     */
    public function setGTk(string $gTk)
    {
        $this->gTk = $gTk;
    }


    /**
     * WeChatOpenLoginModel constructor.
     * @param UserModel $userModel
     */
    public function __construct(UserModel $userModel)
    {
        $this->userModel = $userModel;
    }


    /**
     * 获取登陆二维码
     * @return string
     */
    public function getLoginImg()
    {
        $api = "https://open.weixin.qq.com/connect/qrconnect?appid=wx5cb34fe58d130615&scope=snsapi_login&redirect_uri=https://a.weixin.qq.com/index.html&state=test&login_type=jssdk&self_redirect=default&styletype=&sizetype=&bgcolor=&rst=&href=https://wximg.qq.com/wxp/assets/css/agencyweb_login_v2.css";
        phpQuery::newDocumentFileHTML($api);
        $src = pq('img[class="qrcode-image js_qr_img"]')->eq(0)->attr('src');
        return $src ? "https://open.weixin.qq.com" . $src : "";
    }

    /**
     * 检查是否扫码
     * @param $uuid
     * @return string
     */
    public function checkLoginStatus($uuid): string
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        $api = 'https://long.open.weixin.qq.com/connect/l/qrconnect?uuid=' . $uuid . '&last=404&_=' . $msectime . '110';
        $data = HttpClient::request($this->userModel, $api, "", HttpClient::SaveCookie_Status); //保存文件
//        $data = "window.wx_errcode=402;window.wx_code='405';";
        if (!$data) return "请求数据超时!";

        $regex = "/window.wx_errcode=(.*?);window.wx_code='(.*?)';/is";
        preg_match_all($regex, $data, $matches, PREG_PATTERN_ORDER);
        if (!isset($matches[1][0])) {
            return "解析失败!";
        }

        if ($matches[1][0] != '405') {
            return self::$checkCode[$matches[1][0]] ?? "返回未知错误!";
        }
        $this->wxCode = $matches[2][0];
        return "";

    }


    /**
     * 登陆
     * @return string
     */
    public function login()
    {
        $api = "https://a.weixin.qq.com/cgi-bin/agency/login_auth";
        $referer = 'https://a.weixin.qq.com/index.html?code=' . $this->wxCode . '&state=test';
        $string = HttpClient::request($this->userModel, $api, $referer, HttpClient::SaveCookie_Status, HttpClient::getCodeData($this->wxCode));
//        $string = '{"agency_id":"spidb9f0141753","err":"OK","result":0,"ret":0,"review_status":1,"role":2}';
        $data = json_decode($string, true);
        if (isset($data['err']) && $data['err'] == "OK") {
            return "";
        }
        return $data['err'];
    }


    /**
     * 获取首页数据
     * @param int $page
     * @return mixed
     */
    public function getindexdata($page = 1)
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        $api = "https://a.weixin.qq.com/cgi-bin/agency/get_delivery_metrics?page=" . $page . "&page_size=100&search_key=&order_by=&ascending=1&only_collect=0&g_tk=" . $this->gTk . "&_=" . $msectime;
        $infoData = HttpClient::request($this->userModel, $api, "", HttpClient::ReadCookie_Status);
        return $infoData;
    }

    /**
     * 选择appid
     * @param $appid
     * @return bool|mixed|string
     */
    public function putin($appid)
    {
        $api = "http://a.weixin.qq.com/cgi-bin/agency/redirect_mp?appid=" . $appid . "&g_tk=" . $this->gTk . "&mgr_type=1";
        $info = HttpClient::request($this->userModel, $api, "", HttpClient::ReturnCurlInfo_Status);
        return $info;
    }

    /**
     * 不知道干啥
     * @param $token
     * @return bool|mixed|string
     */
    public function putOn($token)
    {
        $api = 'https://mp.weixin.qq.com/promotion/v3/create_campaign_info';
        $referer = 'https://mp.weixin.qq.com/promotion/frame?t=ad_system/common_simple_frame&t1=campaign/edit&token=' . $token . '&from_pos_type=0';

        $info = HttpClient::request($this->userModel, $api, $referer, HttpClient::SaveAndReadCookie_Status);
        return $info;
    }
}